<template>
  <div class="page-cont">
    <van-nav-bar
      title="计划管理"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="list">
      <div class="btn">
        <van-button
          type="info"
          size="small"
          @click="$router.push('/plan/append')"
          block
        >
          + 新增
        </van-button>
      </div>
      <template v-if="list">
        <plan-item
          :plan="plan"
          v-for="(plan, i) in list"
          :key="i"
          @edit="editItem"
        />
      </template>
      <van-empty
        v-if="list && list.length === 0"
        description="还没有数据"
      />
    </div>
  </div>
</template>

<script>
import PlanItem from "./components/PlanItem.vue";
export default {
  name: "PlanPage",
  components: {
    PlanItem
  },
  data() {
    return {
      list: null,
    };
  },
  created() {
    this.getTreeData();
  },
  methods: {
    editItem(item) {
      this.$router.push({
        path: `/plan/${item.bridgeId}/${item.bridgeLocation}`,
        query: {
          json: JSON.stringify(item)
        }
      })
    },
    async getTreeData() {
      this.$toast.loading({  message: '加载中...', forbidClick: true });
      let res = await this.api.GET_PLAN_TREE()

      const data = [];
      Object.keys(res).forEach(key => {
        const item = res[key]
        const itemList = item.map(a => {
          a.name = a.bridgeLocation === 1 ? '左幅' : '右幅'
          return a
        }).sort((a, b) => a.bridgeLocation - b.bridgeLocation)

        const obj = Object.assign({}, item[0], {
          name: key,
          // 计算梁总和
          sliceNum: item.reduce((total, item) => total + item.sliceNum, 0),
          list: itemList,
        })
        data.push(obj)
      })
      this.list = data
      this.$toast.clear();
    },
  }
};
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
